extends CharacterBody2D

# 配置参数
@export var max_speed = 30.0      # 最大冲刺速度
@export var acceleration_time = 1.5 # 加速到最大速度的时间（秒）
@export var rest_time = 1.0        # 冲刺后的休息时间（秒）

# 状态变量
enum State {RESTING, CHARGING}
var current_state = State.RESTING
var target_position = Vector2.ZERO  # 冲刺目标位置
var charge_timer = 0.0                # 冲刺计时器
var rest_timer = 0.0                  # 休息计时器
var isWall = false

# 节点引用
var player = null
@onready var eyes = $Eyes
@onready var wallActive = $WallActive

func _ready():
	eyes.connect("body_entered", bodyEntered)
	eyes.connect("body_exited", bodyExited)
	wallActive.connect("body_entered", wallEnter)

func wallEnter(_wall):
	isWall = true
	
func bodyEntered(body):
	if body.name == "Player":
		player = body
	
	
func bodyExited(body):
	if body.name == "Player":
		player = null
	
	
func _physics_process(delta):
	match current_state:
		State.RESTING:
			# 休息状态，等待计时器结束
			rest_timer -= delta
			if rest_timer <= 0.0:
				start_charge()
		
		State.CHARGING:
			# 持续面向玩家方向
			if player:
				var direction = (player.global_position - global_position).normalized()
				rotation = direction.angle()
			
			# 速度插值加速
			charge_timer += delta
			var t = charge_timer / acceleration_time
			var current_speed = lerp(0.0, max_speed, min(t, 1.0))
			velocity = Vector2.RIGHT.rotated(rotation) * current_speed
			
			# 移动并检测碰撞
			move_and_slide()
			
			# 碰撞后处理
			if isWall:
				enter_rest()


func start_charge():
	if not player:
		return
	
	# 锁定冲刺目标位置（玩家当前位置）
	target_position = player.global_position
	current_state = State.CHARGING
	charge_timer = 0.0
	isWall = false


func enter_rest():
	current_state = State.RESTING
	rest_timer = rest_time
	velocity = Vector2.ZERO  # 停止移动


# 可选：在编辑器中显示冲刺目标位置
func _draw():
	if current_state == State.CHARGING:
		draw_line(Vector2.ZERO, (target_position - global_position), Color.RED, 2.0)
